﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;

/// <summary>
/// Name ::: Mr. Akawit Tangkupatanonth
/// Date ::: 16/03/2014
/// Description ::: Add new class for Validate
/// </summary>

namespace RBAC.Web.Utilities
{
    public class Validates
    {
        #region Single Validate Function(validate themself)

        //validate this string is email
        public bool IsValidEmail(string strIn)
        {
            // Return true if strIn is in valid e-mail format.
            return Regex.IsMatch(strIn, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
        }

        //validate this string is URL 
        public bool IsValidURL(string strIn)
        {
            return Regex.IsMatch(strIn, @"^(http|https)://([\w+?\.\w+])+([a-zA-Z0-9\~\!\@\#\$\%\^\&\*\(\)_\-\=\+\\\/\?\.\:\;\'\,]*)?$", RegexOptions.IgnoreCase);
        }

        //validate this string has numberic only
        public bool IsNumbericOnly(string strIn)
        {
            return Regex.IsMatch(strIn, @"^[0-9]*$");
        }

        //validate this string has character only
        public bool IsCharacterOnly(string strIn)
        {
            return Regex.IsMatch(strIn, @"^[a-zA-Z]$");
        }

        //validate this string not allow special character
        public bool NotAllowSpecialCharacter(string strIn)
        {
            return Regex.IsMatch(strIn, @"^[0-9a-zA-Z]$");
        }

        //validate this string has not empty
        public bool IsNotEmpty(string strIn)
        {
            return !String.IsNullOrEmpty(strIn);
        }

        //validate this string is ThaiNationalID
        public bool IsValidThaiNationalID(string strIn)
        {
            for (int i = 0; i < strIn.Length; i++)
            {
                char c = strIn.Substring(i, 1).ToCharArray()[0];

                if (!char.IsNumber(c)) return false;
            }

            if (strIn.Trim().Length != 13) return false;

            int sumValue = 0;

            for (int i = 0; i < strIn.Length - 1; i++)
                sumValue += int.Parse(strIn[i].ToString()) * (13 - i);

            int v = 11 - (sumValue % 11);
            string strV = v.ToString();

            if (strV.Length > 1)
                strV = strV.Substring(1, 1);


            return strIn[12].ToString() == strV;
        }

        //validate this image is image type or not
        public bool IsImageType(HttpPostedFileBase[] images)
        {
            string[] formats = new string[] { ".jpg", ".png", ".gif", ".jpeg", ".pdf", ".tiff" };

            try
            {
                foreach (HttpPostedFileBase image in images)
                {
                    if (!image.ContentType.Contains("image")) return false;

                    if (!formats.Any(item => image.FileName.EndsWith(item, StringComparison.OrdinalIgnoreCase))) return false;
                }
            }
            catch { return false; }

            return true;
        }

        #endregion

        #region Single Validate Function(with value)

        //validate this string length must not less than number
        public bool AtLeastLength(string strIn, string number)
        {
            return strIn.Length - int.Parse(number) >= 0;
        }

        //validate this string length must not more than number
        public bool AtMostLength(string strIn, string number)
        {
            return strIn.Length - int.Parse(number) <= 0;
        }



        //validate this image has width and height more than rule or not
        public bool IsImageSize(HttpPostedFileBase[] images, string width, string height)
        {
            foreach (HttpPostedFileBase image in images)
            {
                if (int.Parse(width) * int.Parse(height) < image.ContentLength) return false;
            }

            return true;
        }

        //validate this image is image type or not
        public bool IsFileType(HttpPostedFileBase[] files, string fileType)
        {
            string[] formats = fileType.Split('&');

            foreach (HttpPostedFileBase file in files)
            {
                if (!formats.Any(item => file.FileName.EndsWith(item, StringComparison.OrdinalIgnoreCase))) return false;
            }

            return true;
        }

        #endregion

        //validate dateFrom string must be less than or equal dateTo
        public bool ValidateDateFromDateTo(DateTime dateFrom, DateTime dateTo)
        {
            return DateTime.Compare(dateFrom, dateTo) < 0;
        }

        //validate value1 must more than value2
        public bool ValidateValue1MorethanValue2(string value1, string value2)
        {
            return float.Parse(value1) > float.Parse(value2);
        }

        //validate this string in range [for int or float]
        public bool IsValueRange(string strIn, string min, string max, string type)
        {
            if (type == "Int")
                return (int.Parse(strIn) <= int.Parse(max)) || (int.Parse(strIn) >= int.Parse(min));
            else if (type == "Float")
                return (float.Parse(strIn) <= float.Parse(max)) || (float.Parse(strIn) >= float.Parse(min));
            else
                return false;
        }

        //validate this string in range [for date or time]
        public bool IsValueRange(DateTime strdate, string min, string max, string type)
        {
            CultureInfo th = System.Globalization.CultureInfo.GetCultureInfo("th-TH");

            if (type == "Date")
            {
                DateTime DTFrom = DateTime.ParseExact(min, "dd/MM/yyyy", th);
                DateTime DTTo = DateTime.ParseExact(max, "dd/MM/yyyy", th);

                return strdate >= DTFrom && strdate < DTTo;
            }
            else if (type == "Time")
            {
                TimeSpan TSFrom = new TimeSpan(int.Parse(min.Split(':')[0]), int.Parse(min.Split(':')[1]), int.Parse(min.Split(':')[2])); //[0] : hour; [1] : min; [2] : secound
                TimeSpan TSTo = new TimeSpan(int.Parse(max.Split(':')[0]), int.Parse(max.Split(':')[1]), int.Parse(max.Split(':')[2])); //[0] : hour; [1] : min; [2] : secound
                TimeSpan now = DateTime.Now.TimeOfDay;

                return (now >= TSFrom) && (now < TSTo);
            }
            else
                return false;
        }

        //validate require at least word in string
        public bool ValidateRequireWording(string text, string value, string type)
        {
            bool result = false;

            string[] words = value.Split('&');

            if (type == "all")
            {
                result = true;

                foreach (string word in words)
                {
                    if (!Regex.IsMatch(text, @"\b" + word + "\b"))
                    {
                        result = false;
                    }
                }
            }
            else if (type == "some")
            {
                foreach (string word in words)
                {
                    if (Regex.IsMatch(text, @"\b" + word + "\b"))
                    {
                        result = true;
                    }
                }
            }

            return result;
        }
    }
}